package com.luo.auth.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import com.luo.auth.annotation.CurrentUser;
import com.luo.auth.constant.Constants;
import com.luo.auth.pojo.TokenObj;
import com.luo.partner.dao.model.TabUsrs;
import com.luo.partner.service.TabUsrsService;

@Component
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
	private Logger logger = LoggerFactory.getLogger(CurrentUserMethodArgumentResolver.class);

    @Autowired
    private TabUsrsService usrsService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数类型是User并且有CurrentUser注解则支持
        if ((parameter.getParameterType().isAssignableFrom(TabUsrs.class) &&
                parameter.hasParameterAnnotation(CurrentUser.class))) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //取出鉴权时存入的登录用户Id
    	TokenObj token = (TokenObj) webRequest.getAttribute(Constants.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
        if (token != null) {
        	if (token.getSource() == 0) {
				// 用户
                return usrsService.get(token.getId());
			}
        }
        throw new MissingServletRequestPartException(Constants.CURRENT_USER_ID);
    }
}
